package com.css.common.security.utils;

import com.css.common.security.constant.SecurityConstants;
import com.css.common.security.support.CssUser;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * SecurityUtil
 * 安全工具类
 *
 * @author hanyx
 * @date 2019/05/04
 */
@UtilityClass
public class SecurityUtil {
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     */
    public CssUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof CssUser) {
            return (CssUser) principal;
        }
        return null;
    }

    /**
     * 获取用户
     */
    public CssUser getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }

    /**
     * 获取用户角色信息
     *
     * @return 角色集合
     */
    public List<String> getRoles() {
        Authentication authentication = getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        List<String> roleIds = new ArrayList<>();
        authorities.stream()
                .filter(granted -> StringUtils.startsWith(granted.getAuthority(), SecurityConstants.ROLE))
                .forEach(granted -> {
                    String id = StringUtils.removeStart(granted.getAuthority(), SecurityConstants.ROLE);
                    roleIds.add(id);
                });
        return roleIds;
    }

}
